//
//  DXStatuesViewModel.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/10.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit

class DXStatuesViewModel: NSObject {

    var statuesMoel:DXStatuseModel?
    
//    转发微博的富文本
    var retweetedStatuesAttribute:NSMutableAttributedString?
//    转发微博特殊文本的范围数组
    var retweetedStatuesLinks:[DXMatchRegModel]?

    
//    原创微博的富文本
    var originalStatuesAttribute:NSMutableAttributedString?
//    原创微博特殊文本的范围数组
    var originalStatuesLinks:[DXMatchRegModel]?

//    会员图标
    var mbrankImg:UIImage?{
//    计算性属性
      
        guard let membership_level =  statuesMoel?.user?.mbrank else{
        
        return nil
        }
        if membership_level > 0 && membership_level < 7{
        
           return UIImage(named: "common_icon_membership_level\(membership_level)")
        
        }else{
        return nil
        }
    }

//    认证图标
     var verifiedIMG:UIImage?
//    转发微博内容文字
    var retweetedText:String?
    
//     转发图标文字
    var repostString:String{
       
    return judgeToolBarCount(statuesMoel?.reposts_count, title: "转发")
        
    }
//    评论图标文字
    var commentString:String{
    return judgeToolBarCount(statuesMoel?.comments_count, title: "评论")
    }
//    点赞图标文字
    var attitudeString:String{
    return judgeToolBarCount(statuesMoel?.attitudes_count, title: "赞")
    
    }
//    来源状态文字
    var scoureText:String?
 
//    微博发表时间
    var createdText:String {
      return   NSDate.sinaDate((statuesMoel?.created_at)!).sinaCreatedSting
        
//       return getCreatedText((statuesMoel?.created_at)!)
    
    }
    //    转发微博是否为空
    var hasRetweeted_status:Bool{
        
        if (statuesMoel!.retweeted_status) == nil {
            //            转发微博为空
            return false
        }else{
            //            转发微博不为空
            return true
        }
    }
    
    init(statues:DXStatuseModel) {
        super.init()
        statuesMoel = statues
        judgeVerifiedIMG()
        appendRetweeText()
        getScoureText()
        let retweetedResult = getStatuesAttribute(retweetedText)
        retweetedStatuesAttribute = retweetedResult.attr
        retweetedStatuesLinks = retweetedResult.links
        let originalResult =  getStatuesAttribute( statuesMoel?.text)
        originalStatuesAttribute = originalResult.attr
        originalStatuesLinks = originalResult.links
        
        
      }
//    MARK:- 得到原创微博的富文本
    private func getStatuesAttribute(text:String?)->(attr:NSMutableAttributedString?,links:[DXMatchRegModel]?){
//        有文本字符串
        guard let statuesText = text else {
        return (nil,nil)
        }
        var linkMatchResult:[DXMatchRegModel] =  [DXMatchRegModel]()
//        正则表达式,搜索到目标字符串,并记录到字典中
        let matchModels = statuesText.matchRegexString("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]")
//        由文本字符串生成富文本字符串
        let attributeM = NSMutableAttributedString(string: statuesText)
//       遍历匹配字符串,是否含有表情模型
        for model in matchModels.reverse(){
            if  let resultEmotion = DXEmotionViewModel.sharedEmoton.matchEmotionWithString(model.matchString!){
//                如果含有对应的表情模型,则生成对应的表情富文本
            let attachmet = DXEmotionAttachment(emotion: resultEmotion)
//                用新生成的表情富文本替换对应目标字符
            attributeM.replaceCharactersInRange(model.matchRange!, withAttributedString: attachmet.getAttributString(UIFont.systemFontOfSize(kstatuesFontSize)))
            }
        }
        
        let linkRnges = addEffect(attributeM, regex: "@[^\\s^:^,]+")
         let themeRnges = addEffect(attributeM, regex: "#[^#]+#")
         let netRnges = addEffect(attributeM, regex: "http(s)?://[^\\s^\\u4e00-\\u9fa5]+")
        linkMatchResult = linkRnges+themeRnges+netRnges
        return (attributeM , linkMatchResult)
    }
    // MARK: - 匹配特殊效果
    private func addEffect(attributeStr:NSMutableAttributedString,regex:String)->[DXMatchRegModel]{
//        @高亮
        let matchModels = attributeStr.string.matchRegexString(regex)
        for matchModel in matchModels{
        attributeStr.addAttribute(NSForegroundColorAttributeName, value:RGBCorlor(R: 80, G: 125, B: 175), range: matchModel.matchRange!)
        }
        return matchModels
    }



    
//   MARK:- scoureText 来源文字的截取
    private func getScoureText(){
    
        if  let text =  statuesMoel?.source {
            if text.containsString("\">"){
                
        let startRange = text.rangeOfString("\">")!.endIndex
        let endRange =  text.rangeOfString("</")!.startIndex
        let Scoure = text.substringWithRange(startRange..<endRange)
        scoureText = "来自 \(Scoure)"
    }
  }
}
//   MARK:- 转发微博内容的拼接
    private func appendRetweeText(){
        if let retweetedStatus = statuesMoel?.retweeted_status{
         retweetedText = "@\(retweetedStatus.user!.name!):" + "\(retweetedStatus.text!)"
        }
    }
    
//   MARK:- 图标文字显示逻辑判断
// count 11010 --> "1.1万"
// count 10900 --> "1万"
    private func  judgeToolBarCount(count:Int? ,title:String)->String{
        if count == 0 || count == nil {
        return title
        }else{
            if count! < 10000{
            
            return "\(count!)"
            }else{
           let result = CGFloat(count!)/1000/10
            
           let resultString = "\(result)万"
                if resultString .containsString(".0"){
                
        return resultString.stringByReplacingOccurrencesOfString(".0", withString: "")
                
                }else{
                 return resultString
                }
            }
        }
    }
    
//   MARK:- 认证图标的判断逻辑
    private func judgeVerifiedIMG(){
        
        let verified_level =  statuesMoel?.user?.verified
        if verified_level == nil {
            verifiedIMG = nil
        }else{
            //        认证类型 -1：没有认证; 1:认证用户，2,3,5: 企业认证，220: 达人
            switch verified_level! {
                
            case 1: verifiedIMG = UIImage(named: "avatar_vip")
                
            case 2,3,5: verifiedIMG = UIImage(named: "avatar_enterprise_vip")
                
            case 220: verifiedIMG = UIImage(named: "avatar_grassroot")
                
            default : verifiedIMG = nil
                
            }
        }
    }
}
